<template>
  <div class="detail-page">
    <div class="container">
      <div class="detail-container card">
        <!-- 文章内容 -->
        <div class="detail-content">
          <div class="detail-header">

            <h1 class="detail-title">{{ article.title }}</h1>
            <div class="detail-meta">
              <div class="detail-author">
                <el-avatar :size="35" :src="article.authorAvatar" class="author-avatar" @click="goToUser(article.authorId)"></el-avatar>
                <div class="author-info">
                  <div class="author-name">{{ article.authorName }}</div>
                  <div class="publish-time">{{ article.publishTime }}</div>
                </div>
                
              </div>
              <el-button 
                size="small" 
                :type="article.isFollowed ? 'primary' : 'default'" 
                v-if="username!==article.authorName"
                @click="toggleFollow">
                {{ article.isFollowed ? '已关注' : '关注' }}
              </el-button>
            </div>
            <div class="detail-category">
              <el-tag size="small" effect="plain" @click="goToCategory(article.categoryId)">
                {{ getCategoryName(article.categoryId) }}
              </el-tag>
            </div>
            <!-- 添加文章标签 -->
            <div class="detail-tags" v-if="article.tags">
              <span class="tags-label">标签:</span>
              <div class="tags-list">
                <el-tag
                  v-for="tag in getTagsList(article.tags)"
                  :key="tag"
                  size="default"
                  effect="plain"
                  class="article-tag"
                  type="success"
                >
                  <el-icon class="tag-icon"><Collection /></el-icon>
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
                <!-- 添加封面图片 -->
                <div class="detail-cover" v-if="article.cover">
              <img :src="article.cover" alt="文章封面">
            </div>
          <div class="detail-body" v-html="article.content"></div>
          
          <div class="detail-actions">
            <div class="action-left">
              <div 
                class="action-btn" 
                :class="{ active: article.isLiked }" 
                @click="toggleLike">
                <el-icon><Thumb /></el-icon>
                <span>{{ article.isLiked ? '已点赞' : '点赞' }} {{ article.likes }}</span>
              </div>
              <div class="action-btn" @click="focusComment">
                <el-icon><ChatDotRound /></el-icon>
                <span>评论 {{ article.comments.length }}</span>
              </div>
              <!-- 添加删除按钮,仅作者可见 -->
              <div 
                v-if="isAuthor" 
                class="action-btn delete-btn" 
                @click="confirmDelete">
                <el-icon><Delete /></el-icon>
                <span>删除文章</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 评论区 -->
        <div class="comments-section">
          <div class="comments-header">
            <h3>全部评论 ({{ article.comments.length }})</h3>
          </div>
          
          <!-- 评论列表 -->
          <div class="comment-list" v-if="article.comments.length > 0">
            <div v-for="comment in article.comments" :key="comment.id" class="comment-item">
              <div class="comment-user">
                <el-avatar :size="35" :src="comment.avatar"  @click="goToUser(comment.userIds)"></el-avatar>
                <div class="comment-user-info">
                  <div class="comment-username">{{ comment.nickname }}</div>
                  <div class="comment-time">{{ comment.time }}</div>
                </div>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-actions">
                <span @click="replyComment(comment)">
                  <el-icon><ChatSquare /></el-icon>
                  回复
                </span>
              </div>
              
              <!-- 回复列表 -->
              <div class="reply-list" v-if="comment.replies && comment.replies.length > 0">
                <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                  <div class="reply-user">
                    <el-avatar :size="30" :src="reply.avatar"  @click="goToUser(reply.userIds)"></el-avatar>
                    <div class="reply-user-info">
                      <span class="reply-username">{{ reply.nickname }}</span>
                      <span class="reply-to" v-if="reply.replyTo"> 回复 @{{ reply.replyTo }}</span>
                      <div class="reply-time">{{ reply.time }}</div>
                    </div>
                  </div>
                  <div class="reply-content">{{ reply.content }}</div>
                  <div class="reply-actions">
                    <span @click="replyToReply(comment, reply)">
                      <el-icon><ChatSquare /></el-icon>
                      回复
                    </span>
                  </div>
                </div>
              </div>
              
              <!-- 回复输入框 -->
              <div class="reply-form" v-if="replyingTo && replyingTo.id === comment.id">
                <el-input
                  v-model="replyContent"
                  type="textarea"
                  :rows="2"
                  placeholder="写下你的回复..."
                  resize="none"
                ></el-input>
                <div class="reply-form-actions">
                  <el-button size="small" @click="cancelReply">取消</el-button>
                  <el-button size="small" type="primary" @click="submitReply">回复</el-button>
                </div>
              </div>
            </div>
          </div>
          <div class="no-comments" v-else>
            暂无评论，快来发表你的看法吧！
          </div>
          
          <!-- 评论输入框 -->
          <div class="comment-form" ref="commentForm">
            <h4 class="comment-form-title">发表评论</h4>
            <el-input
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="写下你的评论..."
              resize="none"
            ></el-input>
            <div class="comment-form-footer">
              <div class="comment-tips">文明评论，理性发言</div>
              <el-button type="primary" @click="submitComment">发表评论</el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 相关推荐 -->
      <div class="related-section card">
        <div class="related-header">
          <h3>相关推荐</h3>
        </div>
        <div class="related-list">
          <div 
            v-for="item in relatedArticles" 
            :key="item.id" 
            class="related-item"
            @click="goToDetail(item.id)">
            <div class="related-title">{{ item.title }}</div>
            <div class="related-meta">
              <span>{{ item.views }} 阅读</span>
              <span>{{ item.likes }} 点赞</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Thumb, ChatDotRound, ChatSquare, Delete, Collection } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'


const route = useRoute()
const router = useRouter()
const commentForm = ref(null)

// 数据状态
const articleId = ref(parseInt(route.params.id))
const commentContent = ref('')
const replyContent = ref('')
const replyingTo = ref(null)
const replyingToReply = ref(null)
const username = localStorage.getItem('username')
const follow_id = localStorage.getItem('id')
const followerId = parseInt(follow_id);
const article = ref({
  id: 0,
  title: '',
  content: '',
  cover: '',
  tags: '',
  authorName: '',
  authorAvatar: '',
  publishTime: '',
  views: 0,
  likes: 0,
  img: '',
  isLiked: false,
  isFollowed: false,
  categoryId: 0,
  comments: []
})

const relatedArticles = ref([])
const categories = ref([])
const isLoading = ref(false)
const authorId = ref(null)
// 生命周期钩子
onMounted(() => {
  fetchArticle()
  fetchRelatedArticles()
  fetchCategories()
})


const goToUser = (id) => {
  if (id !== followerId) {
    router.push(`/user/${id}`)
  }
}

// 方法
// 获取文章详情
const fetchArticle = async () => {
  isLoading.value = true
  try {
    const res = await request.get(`/articles/detail/${articleId.value}`)
    
    if (res.data.code === '200') {
      const articleData = res.data.data
       authorId.value = res.data.data.authorId
      console.log('-articleData.id-',res.data.data.img);
      
      // 更新文章数据
      article.value = {
        id: articleData.id,
        title: articleData.title,
        content: articleData.content,
        authorId: articleData.authorId,
        coverUrl: articleData.coverImg,
        authorName: articleData.nickName || articleData.username || '匿名用户',
        authorAvatar: articleData.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        publishTime: articleData.createTime,
        views: articleData.views || 0,
        likes: articleData.likes || 0,
        tags: articleData.tags,
        isLiked: articleData.isLiked || false,
        isFollowed: articleData.isFollowed || false,
        categoryId: articleData.categoryId,
        img: articleData.img,
        cover: articleData.cover,
        comments: []
      }
      
      // 获取文章评论
      fetchComments()
      
      // 更新阅读量
      updateViews()

      //是否点赞
      isLikedload()

      //是否关注
      isFollowedload()
      
    } else {
      ElMessage.error(res.data.msg || '获取文章详情失败')
    }
  } catch (error) {
    console.error('获取文章详情出错:', error)
    ElMessage.error('获取文章详情失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 获取评论列表
const fetchComments = async () => {
  try {
    const res = await request.get(`/comment/list/${articleId.value}`)
    
    if (res.data.code === '200') {
      // 将评论数据转换为需要的格式
      article.value.comments = formatComments(res.data.data || [])
      
      console.log('-article.value.comments-',article.value.comments);
    } else {
      console.error('获取评论失败:', res.data.msg)
    }
  } catch (error) {
    console.error('获取评论出错:', error)
  }
}

// 格式化评论数据
// 修改 formatComments 方法
const formatComments = (comments) => {
  // 只处理一级评论和直接回复
  const topLevelComments = comments.filter(c => !c.parentId)
  
  console.log('-topLevelComments-',topLevelComments);
  
  return topLevelComments.map(comment => ({
    id: comment.id,
    username: comment.username,
    nickname: comment.nickname || comment.username,
    avatar: comment.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    content: comment.content,
    time: comment.createTime,
    userIds: comment.userId,
    replies: comments
      .filter(c => c.parentId === comment.id)
      .map(reply => ({
        id: reply.id,
        username: reply.username,
        nickname: reply.nickname || reply.username,
        avatar: reply.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        content: reply.content,
        time: reply.createTime,
        userIds: reply.userId,
        replyTo: reply.replyTo || comment.username // 默认回复给评论作者
      }))
  }))
}

// 修改 submitReply 方法
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空')
    return
  }
  
  try {
    const data = {
      articleId: articleId.value,
      userId: followerId,
      parentId: replyingTo.value.id,
      content: replyContent.value,
      replyTo: replyingToReply.value ? replyingToReply.value.nickname : replyingTo.value.nickname
    }
    
    const res = await request.post('/comment/reply', data)
    
    if (res.data.code === '200') {
      fetchComments()
      replyContent.value = ''
      replyingTo.value = null
      replyingToReply.value = null
      alert('回复发表成功,等待审核')
    } else {
      ElMessage.error(res.data.msg || '回复发表失败')
    }
  } catch (error) {
    console.error('提交回复失败:', error)
    ElMessage.error('回复发表失败，请稍后重试')
  }
}

// 获取相关文章
const fetchRelatedArticles = async () => {
  try {
    const res = await request.get('/articles/related', {
      params: {
        categoryId: article.value.categoryId,
      }
    })
    
    if (res.data.code === '200') {
      relatedArticles.value = res.data.data.map(item => ({
        id: item.id,
        title: item.title,
        views: item.views || 0,
        likes: item.likes || 0,
        comments: item.comments || 0
      }))
    } else {
      console.error('获取相关文章失败:', res.data.msg)
    }
  } catch (error) {
    console.error('获取相关文章出错:', error)
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/categories/list')
    
    if (res.data.code === '200') {
      categories.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)
    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}

// 更新阅读量
const updateViews = async () => {
  try {
    await request.post(`/articles/view/${articleId.value}`)
  } catch (error) {
    console.error('更新阅读量失败:', error)
  }
}

const getCategoryName = (id) => {
  const category = categories.value.find(item => item.id === id)
  return category ? category.name : '未分类'
}

const goToCategory = (id) => {
  router.push(`/category/${id}`)
}


const goToDetail = (id) => {
  if (id !== articleId.value) {
    router.push(`/detail/${id}`)
    // 刷新页面数据
    articleId.value = id
    fetchArticle()
    fetchRelatedArticles()
    // 滚动到顶部
    window.scrollTo(0, 0)
  }
}

const isLikedload = async() => {
const isLikes = await request.post(`/articles/isLike/`, {
        articleId: articleId.value,
        userId: followerId
      })
      console.log('isLikes',isLikes.data.data);
      
      if (isLikes.data.data === true) {
        article.value.isLiked = true;
    }

    }

const isFollowedload = async() => {
const isFollow = await request.post(`/follow/isFollow/`, {
        followerId: followerId,
        followingId: authorId.value
      })
      console.log('isFollow',isFollow.data.data);
      
      if (isFollow.data.data === true) {
        article.value.isFollowed = true;
    }

    }
// 点赞文章
const toggleLike = async () => {
  try {
    if(article.value.isLiked) {
      // 取消点赞
      // 1. 删除点赞记录
      const delRes = await request.post(`/articles/unLike`, {
        articleId: articleId.value,
        userId: followerId
      })
      if(delRes.data.code === '200') {
        article.value.likes--
        article.value.isLiked = false
        ElMessage.success('已取消点赞')
      }else{
        ElMessage.error('取消点赞失败')
      }
      
    } else {
      // 添加点赞
      // 1. 添加点赞记录

      const addRes = await request.post(`/articles/like/`, {
        articleId: articleId.value,
        userId: followerId
      })

      
      if(addRes.data.code === '200') {
        article.value.likes++
        article.value.isLiked = true
        ElMessage.success('点赞成功')
      }else{
        ElMessage.error('更新点赞数失败')
      }
      
    }
  } catch (error) {
    console.error('点赞/取消点赞失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 关注/取消关注作者
const toggleFollow = async () => {
  try {
    
    if(article.value.isFollowed) {
      // 取消关注
      // 1. 删除关注记录
      const delRes = await request.post(`/follow/unFollow`, {
        followingId: authorId.value,
        followerId: followerId
      })
      if(delRes.data.code !== '200') {
        ElMessage.error(delRes.data.msg || '取消关注失败')
        return
      }
      
      // 2. 更新关注状态
      article.value.isFollowed = false
      ElMessage.success('已取消关注')
    } else {
      // 添加关注
      // 1. 添加关注记录
      const addRes = await request.post(`/follow/follow`, {
        followingId: authorId.value,
        followerId: followerId
      })
      if(addRes.data.code !== '200') {
        ElMessage.error(addRes.data.msg || '关注失败')
        return
      }
      
      // 2. 更新关注状态
      article.value.isFollowed = true
      ElMessage.success('关注成功')
    }
  } catch (error) {
    console.error('关注/取消关注失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

const focusComment = () => {
  commentForm.value.scrollIntoView({ behavior: 'smooth' })
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('评论内容不能为空')
    return
  }
  
  try {
    const res = await request.post('/comment/add', {
      articleId: articleId.value,
      userId: followerId,
      content: commentContent.value
    })
    
    if (res.data.code === '200') {
      // 重新获取评论列表
      fetchComments()
      commentContent.value = ''
      alert('评论发表成功,等待审核')
    } else {
      ElMessage.error(res.data.msg || '评论发表失败')
    }
  } catch (error) {
    console.error('提交评论失败:', error)
    ElMessage.error('评论发表失败，请稍后重试')
  }
}

const replyComment = (comment) => {
  replyingTo.value = comment
  replyingToReply.value = null
  replyContent.value = ''
}

const replyToReply = (comment, reply) => {
  replyingTo.value = comment
  replyingToReply.value = reply
  replyContent.value = ''
}

const cancelReply = () => {
  replyingTo.value = null
  replyingToReply.value = null
  replyContent.value = ''
}



// 判断当前用户是否为文章作者
const isAuthor = computed(() => {
  return followerId === authorId.value
})

// 删除文章确认
const confirmDelete = () => {
  ElMessageBox.confirm(
    '确定要删除这篇文章吗？删除后将无法恢复',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(() => {
    deleteArticle()
  })
  .catch(() => {})
}

// 删除文章
const deleteArticle = async () => {
  try {
    const res = await request.delete(`/articles/delete/${articleId.value}`)
    
    if (res.data.code === '200') {
      ElMessage.success('文章已删除')
      router.push('/') // 删除成功后返回首页
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除文章失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  }
}

// 处理标签字符串转数组
const getTagsList = (tags) => {
  if (!tags) return []
  return tags.split(',').map(tag => tag.trim()).filter(tag => tag)
}
</script>

<style scoped>
.detail-page {
  padding: 20px 0;
}

.detail-container {
  margin-bottom: 20px;
}

.detail-cover {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.detail-cover img {
  width: 100%;
  height: auto;
  max-height: 400px;
  object-fit: cover;
  display: block;
}

.detail-title {
  font-size: 26px;
  font-weight: bold;
  margin-bottom: 15px;
  line-height: 1.4;
}

.detail-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.detail-author {
  display: flex;
  align-items: center;
}

.author-info {
  margin-left: 10px;
}

.author-name {
  font-weight: bold;
  font-size: 15px;
}

.publish-time {
  font-size: 13px;
  color: #999;
}

.detail-category {
  margin-bottom: 20px;
}

.detail-tags {
  margin: 25px 0;
  display: flex;
  align-items: center;
}

.tags-label {
  color: #333;
  margin-right: 15px;
  font-size: 15px;
  font-weight: 500;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.article-tag {
  cursor: pointer;
  font-size: 14px;
  padding: 8px 15px;
  border-radius: 4px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
}

.tag-icon {
  margin-right: 5px;
  font-size: 16px;
}

.article-tag:hover {
  opacity: 0.85;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.detail-body {
  line-height: 1.8;
  font-size: 16px;
  color: #333;
}

.detail-body img {
  max-width: 100%;
  margin: 15px 0;
  border-radius: 4px;
}

.detail-body h3 {
  font-size: 18px;
  font-weight: bold;
  margin: 25px 0 15px;
  color: #222;
}

.detail-body p {
  margin-bottom: 15px;
}

.detail-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.action-left, .action-right {
  display: flex;
  gap: 20px;
}

.action-btn {
  display: flex;
  align-items: center;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.action-btn.active {
  color: #409eff;
}

.action-btn:hover {
  color: #409eff;
}

.action-btn .el-icon {
  margin-right: 5px;
}

/* 评论区样式 */
.comments-section {
  padding: 0 25px 25px;
}

.comments-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

.comment-list {
  margin-bottom: 30px;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.comment-user-info {
  margin-left: 10px;
}

.comment-username {
  font-weight: bold;
  font-size: 15px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-content {
  margin-left: 45px;
  margin-bottom: 10px;
  line-height: 1.6;
}

.comment-actions {
  display: flex;
  margin-left: 45px;
  font-size: 13px;
  color: #999;
}

.comment-actions span {
  margin-right: 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.comment-actions span:hover {
  color: #409eff;
}

.comment-actions .el-icon {
  margin-right: 3px;
}

.comment-actions .active {
  color: #409eff;
}

/* 回复区域样式 */
.reply-list {
  margin-left: 45px;
  margin-top: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  padding: 10px;
}

.reply-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-user {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.reply-user-info {
  margin-left: 10px;
  font-size: 14px;
}

.reply-username {
  font-weight: bold;
  color: #333;
}

.reply-to {
  color: #409eff;
}

.reply-time {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.reply-content {
  margin-left: 40px;
  line-height: 1.6;
  font-size: 14px;
}

.reply-actions {
  display: flex;
  margin-left: 40px;
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}

.reply-actions span {
  margin-right: 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.reply-actions span:hover {
  color: #409eff;
}

.reply-form {
  margin-left: 45px;
  margin-top: 10px;
}

.reply-form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  gap: 10px;
}

/* 评论表单 */
.comment-form {
  margin-top: 30px;
}

.comment-form-title {
  margin-bottom: 15px;
  font-size: 16px;
}

.comment-form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.comment-tips {
  color: #999;
  font-size: 13px;
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 30px 0;
}

/* 相关推荐区域 */
.related-section {
  padding: 20px;
}

.related-header {
  margin-bottom: 15px;
  font-size: 18px;
  font-weight: bold;
}

.related-list {
  display: flex;
  flex-direction: column;
}

.related-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s;
}

.related-item:last-child {
  border-bottom: none;
}

.related-item:hover {
  background-color: #f9f9f9;
}

.related-title {
  font-size: 15px;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.related-meta {
  font-size: 12px;
  color: #999;
}

.related-meta span {
  margin-right: 10px;
}

@media screen and (max-width: 768px) {
  .detail-meta {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .detail-meta .el-button {
    margin-top: 10px;
  }
}
</style> 